from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from .api.stock_api import router as stock_router
from .api.realtime_api import router as realtime_router
from .api.auth_api import router as auth_router
from .api.market_api import router as market_router
from .database.database import create_tables
from .services.market_index_service import market_service
import os

# 创建FastAPI应用
app = FastAPI(
    title="股票财务数据分析系统",
    description="基于akshare的股票财务数据获取与分析系统 - 集成三大测试模块",
    version="2.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建数据库表
create_tables()

# 初始化系统数据
def init_system_data():
    """初始化系统数据"""
    from .database.database import SessionLocal, User
    from .services.auth_service import auth_service
    from datetime import datetime

    db = SessionLocal()
    try:
        # 检查是否已有管理员
        admin_count = db.query(User).filter(User.is_admin == True).count()
        if admin_count == 0:
            print("🔧 初始化管理员账号...")

            # 创建默认管理员
            admin_username = "admin"
            admin_password = "admin123"
            admin_email = "admin@example.com"

            hashed_password = auth_service.get_password_hash(admin_password)
            admin_user = User(
                username=admin_username,
                email=admin_email,
                full_name="系统管理员",
                hashed_password=hashed_password,
                is_active=True,
                is_admin=True,
                created_at=datetime.utcnow()
            )

            db.add(admin_user)
            db.commit()

            print("✅ 默认管理员账号创建成功!")
            print(f"   用户名: {admin_username}")
            print(f"   密码: {admin_password}")
            print("   请首次登录后修改密码")
        else:
            print("✅ 管理员账号已存在")

    except Exception as e:
        print(f"⚠️ 初始化管理员账号失败: {e}")
        db.rollback()
    finally:
        db.close()

# 初始化系统数据
init_system_data()

# 启动事件处理
@app.on_event("startup")
async def startup_event():
    """应用启动时自动启动大盘数据采集"""
    try:
        await market_service.start_data_collection()
        print("🚀 大盘数据采集服务已自动启动")
    except Exception as e:
        print(f"⚠️ 大盘数据采集启动失败: {e}")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时停止大盘数据采集"""
    try:
        await market_service.stop_data_collection()
        print("⏹️ 大盘数据采集服务已停止")
    except Exception as e:
        print(f"⚠️ 大盘数据采集停止失败: {e}")

# 包含API路由
app.include_router(stock_router)        # 测试一：股票财务数据
app.include_router(realtime_router)     # 原实时股价数据
app.include_router(market_router)       # 测试二：沪深大盘数据
app.include_router(auth_router)         # 测试三：用户管理系统

# 确保静态文件和模板目录存在
os.makedirs("frontend/static", exist_ok=True)
os.makedirs("frontend/templates", exist_ok=True)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="frontend/static"), name="static")

# 模板配置
templates = Jinja2Templates(directory="frontend/templates")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    """
    财务数据分析页面（测试一）
    """
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
    """
    集成仪表板页面
    """
    return templates.TemplateResponse("dashboard.html", {"request": request})

@app.get("/market", response_class=HTMLResponse)
async def market_page(request: Request):
    """
    测试二：沪深大盘实时数据页面
    """
    return templates.TemplateResponse("market.html", {"request": request})

@app.get("/health")
async def health_check():
    """
    健康检查接口
    """
    return {"status": "healthy", "message": "股票财务数据分析系统运行正常"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
